# -*- coding: utf-8 -*-
# @Time    : 2018-05-17 14:24
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : HouseLoanCnt.py
# @Software: PyCharm

'''eof
name:个人住房贷款笔数
code:HouseLoanCnt
tableName:
columnName:
groups:个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']


def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def ConvertDataType(dataValue, dataType):
    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    return returnData


def HouseLoanCnt():
    try:
        # 信用提示
        icrLoanInfo002LoanList = FormatData("ICRLoanInfo002*Loan")
        if icrLoanInfo002LoanList == [{}]:
            return u'缺失值'
        else:
            returnList = []
            for icrLoanInfo002Loan in icrLoanInfo002LoanList:
                try:
                    # 账户状态
                    state = icrLoanInfo002Loan.get('State')
                    # 贷款种类
                    loanType = icrLoanInfo002Loan.get('LoanType')
                    if state in null_type_list or loanType in null_type_list:
                        returnList.append(None)
                        continue
                    if state in [u"正常", u"逾期", u"呆账"] \
                            and loanType in [u"个人住房贷款",  u"个人住房公积金贷款"]:
                        returnList.append(1)
                    else:
                        returnList.append(0)
                except:
                    returnList.append(None)
                    continue
            returnListNotNone = filter(lambda x:x is not None, returnList)
            if len(returnListNotNone) == 0:
                return u'缺失值'
            else:
                return sum(returnListNotNone)
    except:
        return u'缺失值'


result = HouseLoanCnt()